﻿using System. Windows;
using Microsoft. Phone. Scheduler;
using System. Net;
using NextApp. WP7. UnionLib;
using WP7_JsonLib;
using System;
using System. Xml. Linq;
using NextApp. WP7. Models;
using System. Linq;
using Microsoft. Phone. Shell;

namespace NextApp. WP7. ScheduledTaskAgent_GetNewBlogs
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        #region 固定原始代码
        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent 建構函式，會初始化 UnhandledException 處理常式
        /// </remarks>
        public ScheduledAgent( )
        {
            if ( !_classInitialized )
            {
                _classInitialized = true;
                // 訂閱 Managed 例外狀況處理常式
                Deployment. Current. Dispatcher. BeginInvoke(delegate
                {
                    Application. Current. UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// 發生未處理的例外狀況時要執行的程式碼
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if ( System. Diagnostics. Debugger. IsAttached )
            {
                // 發生未處理的例外狀況; 切換到偵錯工具
                System. Diagnostics. Debugger. Break( );
            }
        }
        #endregion

        /// <summary>
        /// 執行排程工作的代理程式
        /// </summary>
        /// <param name="task">
        /// 叫用的工作
        /// </param>
        /// <remarks>
        /// 這個方法的呼叫時機為叫用週期性或耗用大量資料的工作時
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //反序列化
            RenewBlogs b = JsonUtil. JsonDeSerialize<RenewBlogs>(task. Description);
            if ( b != null )
            {
                this. Process_GetNewBlogs(b);
                ScheduledActionService. LaunchForTest(task. Name, b. Duration);
            }
        }

        private void Process_GetNewBlogs(RenewBlogs b)
        {
            if ( b != null )
            {
				WebClient client = new WebClient( );
				client. Headers[ "User-Agent" ] = b. UserAgent;
                client. DownloadStringCompleted += (s, e) =>
                    {
                        System. Diagnostics. Debug. WriteLine("轮询获取了结果  {0}", e. Result);
                        if ( e.Error != null )
                        {
                            System. Diagnostics. Debug. WriteLine(e. Error. Message);
                            return;
                        }
						XElement x;
						try
						{
							x = XElement. Parse(e. Result);
						}
						catch ( Exception )
						{
							return;
						}
                        PostList postList = new PostList
                        {
                            catalog = this.ToInt32(x. Element("catalog"). Value),
                            postCount = this.ToInt32( x. Element("postCount"). Value),
                            posts = x. Element("posts") == null ?
                                null :
                                x. Element("posts"). Elements("post"). Select(
                                p => new Post
                                {
                                    id = this.ToInt32( p. Element("id"). Value),
                                    title = p. Element("title"). Value,
                                    #region 废弃的代码
                                    //outline = p. Element("outline"). Value,
                                    //commentCount = p. Element("commentCount"). Value. ToInt32( ),
                                    //authorId = p. Element("authorId"). Value. ToInt32( ),
                                    //author = p. Element("author"). Value,
                                    //catalog = p. Element("catalog"). Value. Split(','). Select(c => c. ToInt32( )). ToArray( ),
                                    //pubDate = p. Element("pubDate"). Value,
                                    #endregion
                                }
                            ). ToArray( ),
                        };
                        //然后更新 Tile
                        if ( postList != null )
                        {
                            this. UpdateMainTile(postList, b. title);
                            NotifyComplete( );
                        }
                    };
                client. DownloadStringAsync(new Uri(string. Format("{0}&guid={1}", b. Uri, Guid. NewGuid( )), UriKind. Absolute));
                System. Diagnostics. Debug. WriteLine("轮询开始搜索   {0}", b. Uri);
            }
        }

        private void UpdateMainTile( PostList pList, string title )
        {
            var appTile = ShellTile. ActiveTiles. FirstOrDefault( );
            if ( appTile != null )
            {
                StandardTileData firstTile = new StandardTileData
                {
                    //Title = "麦金",
                    Title = title,
                    BackTitle = string. Format("新文章 : {0}", pList. postCount),
                    Count = pList. postCount,
					BackContent = (pList.posts != null && pList.posts.Length > 0) ? pList.posts[0].title : string.Empty,
                };
                appTile. Update(firstTile);
            }
		}


		#region 辅助方法
		private int ToInt32(string value)
		{
			if ( value == null || value. Length == 0 )
			{
				return 0;
			}
			else
			{
				return Convert. ToInt32(value);
			}
		}
		#endregion
	}
}